package com.booktrading.service.impl;

import com.booktrading.mapper.UserMapper;
import com.booktrading.model.User;
import com.booktrading.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Override
    public User register(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.selectByUsername(user.getUsername());
        if (existingUser != null) {
            return null; // 用户名已存在
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 设置默认角色和状态
        user.setRole("ROLE_USER");
        user.setStatus(1); // 1: 正常状态
        
        // 设置注册时间
        user.setRegisterTime(new Date());
        
        // 设置默认信誉度
        user.setCredibility(100);
        
        // 插入用户记录
        userMapper.insert(user);
        
        return user;
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }

    /**
     * 创建管理员账号
     */
    public User createAdminUser() {
        // 检查管理员账号是否已存在
        User adminUser = userMapper.selectByUsername("admin");
        if (adminUser != null) {
            return adminUser;
        }

        // 创建新的管理员账号
        User user = new User();
        user.setUsername("admin");
        user.setPassword(passwordEncoder.encode("admin")); // 设置默认密码为 admin
        user.setRealName("系统管理员");
        user.setRole("ROLE_ADMIN");
        user.setStatus(1);
        user.setRegisterTime(new Date());
        user.setCredibility(100);

        userMapper.insert(user);
        return user;
    }

    @Override
    public boolean updateUserStatus(Long userId, Integer status) {
        return userMapper.updateStatus(userId, status) > 0;
    }
} 